package com.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import com.beans.UserInfo;
import com.dao.HdfsDao;
import com.dao.UserDao;
import com.dao.impl.HdfsDaoImpl;
import com.dao.impl.UserDaoImpl;

@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
	UserDao userDao=new UserDaoImpl();
	HdfsDao hdfsDao=new HdfsDaoImpl();
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//处理请求中文乱码
		request.setCharacterEncoding("UTF-8");
		
		String flag =request.getParameter("flag");
		
		if(flag.equals("register")) {
			register(request,response );
		}
		
		else if(flag.equals("login")) {
			login(request,response);
		}
		
		else if(flag.equals("logout")) {
			logout(request,response);
		}
	
	}
	
	private void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//清除session信息
		request.getSession().invalidate();
		String script="<script>window.top.location.href='login.jsp'</script>";
		response.getWriter().write(script);
	}

	//用户注册
	private void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String userName =request.getParameter("userName");
		
		//判定是否已经被注册
		UserInfo oldUser = userDao.getUserByName(userName);
		if(oldUser!=null) {
			request.setAttribute("registerFlag",false );
			request.getRequestDispatcher("/register.jsp").forward(request, response);
		}
		else {
			String password =request.getParameter("password");
			String phone =request.getParameter("phone");
			
			UserInfo user=new UserInfo();
			user.setUserName(userName);
			user.setPassword(password);
			user.setPhone(phone);
			
			//在数据库中添加用户信息
			userDao.addUser(user);
			
			//再HDFS上创建用户目录
			hdfsDao.createUserRoot(userName);
			request.setAttribute("registerFlag",true );
			
			//请求的转向
			request.getRequestDispatcher("/register.jsp").forward(request, response);
		}
	}
	
	private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {	
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		
		UserInfo user= userDao.login(userName,password);
		
		if(user!=null) {
			//用户登录以后，要将登录信息放到session中
			request.getSession().setAttribute("session_user", user);
			request.getRequestDispatcher("/index.html").forward(request, response);
		}
		else {
			request.setAttribute("msg", "账号或密码错误，登陆失败");
			request.getRequestDispatcher("/login.jsp").forward(request, response);
			
		}

	}

}